<template>
  <el-select @focus="focus" v-model="model" :loading="loading" placeholder="请选择">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.text"
      :value="item.value">
    </el-option>
  </el-select>
</template>
<script>
export default {
  name: 'RelySelect',
  props: {
    rely: {
      type: [String, Number],
      default: ''
    },
    value: {
      type: [String, Number],
      default: ''
    },
    getOptions: {
      type: Function,
      default: () => {
        return Promise.resolve([])
      }
    },
    first: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      options: [],
      model: '',
      loading: false
    }
  },
  watch: {
    model(val, oldVal) {
      if (val === oldVal || val === this.value) {
        return
      }
      this.$emit('input', val)
    },
    value(val, oldVal) {
      if (val === oldVal || val === this.model) {
        return
      }
      console.log(val, 'value', oldVal, this.model)
      this.model = val
    },
    // 依赖变化了重新获取数据
    rely(val, oldVal) {
      if (val === oldVal) {
        return
      }
      console.log(val, 'rely', oldVal)
      this.options = []
      this.model = ''
    }
  },
  methods: {
    focus() {
      if (!this.options.length) {
        this.loading = true
        this.getOptions(this.rely).then(arr => {
          this.options = arr
        }).finally(_ => {
          this.loading = false
        })
      }
    }
  }
}
</script>
